extern crate jsonwebtoken;
mod token;
pub mod authorized;

use jsonwebtoken::{decode, DecodingKey, EncodingKey, Header, Validation};
use rocket::{http::Method, time::{Duration, OffsetDateTime}};
use rocket_cors::{AllowedHeaders, AllowedOrigins, Cors, CorsOptions};


pub fn get_token() ->String{

    let claims = token::Claims::new("zenghaifeng".to_string(), OffsetDateTime::now_utc(), OffsetDateTime::now_utc()+ Duration::minutes(1));
    let token = jsonwebtoken::encode(&Header::default(), &claims, &EncodingKey::from_secret("zenghaifeng".as_ref())).unwrap();
    return token;
}

pub fn validation(token:&str) -> Result<i32,i32> {
    let mut validation = Validation::new(jsonwebtoken::Algorithm::HS256);
    validation.sub = Some("zenghaifeng".to_string());

    let token_date = match decode::<token::Claims>(token, &DecodingKey::from_secret("zenghaifeng".as_ref()), &validation) {
        Ok(_c) => Ok(1),
        Err(_err) => Err(0),
    };
    return token_date;
}


pub fn make_cors() -> Cors{
    let allowed_origins = AllowedOrigins::some_exact(&[
        "http://127.0.0.1:5173",
        "http://localhost:5173",
    ]);

    CorsOptions{
        allowed_origins,
        allowed_methods: vec![Method::Get,Method::Post,Method::Options].into_iter().map(From::from).collect(),
        allowed_headers: AllowedHeaders::all(),
        /* ::some(&[
            "Authorization",
            "Accept",
            "Access-Control-Allow-Origin",
        ]),
        */
        allow_credentials: true,
        ..Default::default()
    }
    .to_cors()
    .expect("error while building CORS")
}